//
//  MutiltimediaView.m
//  ChildHoodStemp
//
//  Created by xuzuotao on 13-10-6.
//
//

#import "MutiltimediaView.h"
#import "Snsp.pb.h"

#import "ChildHoodUser.h"
#import "UIUtil.h"
//#import "CHPostService.h"
//#import "CHPostManager.h"
#import "ChildHoodService.h"
//#import "CHResourceService.h"
#import "CHSAudioPlayer.h"
//#import "ChildHoodService.h"
#import <AVFoundation/AVFoundation.h>
#import "MicroDef.h"
//#import "CHMessageManager.h"
#import "ChildHoodMessage.h"
#import "CXmppRequestMgr.h"
#import "ChildHoodService.h"
#import "CUserSettingMgr.h"
#import "CUserSettingModel.h"
#import "ChildHoodMessage.h"
#import "VoiceConverter.h"
#import "MBProgressHUD+WZ.h"
#import "Reachability.h"
#import "CFolderMgr.h"
#import "RMDownloadIndicator.h"

@interface MutiltimediaView()<CHSAudioPlayerDelegate, UIGestureRecognizerDelegate,UIScrollViewDelegate>
{
    SNSPMaterialType _type;
    BOOL _audioIsExist;
    RMDownloadIndicator *_processLal;
}
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) UIButton *playButton;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property(nonatomic,retain)RMDownloadIndicator *processLal;
@property (nonatomic, strong) UIImageView *photoImageView;

//-(void)onResourceDownloaded:(NSNotification*)notification;

-(void)showImageData;

- (void)scanImgMethod:(id)sender;

-(void)showImage:(UIImage*)image;

-(BOOL)handlAudio;

-(void)handlImage;
@property (nonatomic, strong) CUserSettingModel *setting;


@end


@implementation MutiltimediaView
@synthesize voiceType = _voiceType;
@synthesize fileUri = _fileUri;
@synthesize processLal = _processLal;
-(void)setRedpacketInfo:(NSString *)redpacketInfo
{
    _redpacketInfo = redpacketInfo;
    [self handlRedPacket];
}
- (void)scanImgMethod:(id)sender
{
    //  [[NSNotificationCenter defaultCenter] postNotificationName:GetImgMemory object:sender];
}

-(void)dealloc
{
    //    NSLog(@"MutiltimediaView dealloc!");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

-(void)setImgVoiceOrigin
{
    
    self.delegate = nil;
    self.photoImageView = nil;
    UIImageView *img_voice = (UIImageView *)[self viewWithTag:123647];
    UILabel *timelabel = (UILabel *)[self viewWithTag:133333];
    if (_voiceType == CHSVoiceTypeSended) {
        
        CGSize size = img_voice.image.size;
        
        img_voice.frame = CGRectMake(self.frame.size.width - 20 - size.width, (self.frame.size.height-size.height)/2, size.width, size.height);
        timelabel.frame = CGRectMake(self.frame.size.width - 55 - size.width, 0, 30, self.frame.size.height);
        
    }
    else
    {
        CGSize size = img_voice.image.size;
        
        img_voice.frame = CGRectMake(20, (self.frame.size.height-size.height)/2, size.width, size.height);
        timelabel.frame = CGRectMake(20 + size.width + 5, 0, 30, self.frame.size.height);
    }
}

- (id)initWithFrame:(CGRect)frame
{
    _fileUri = nil;
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _isFromChat = NO;
        //        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResourceUploaded:) name:@"NOTIFY_UPLOAD_PRCESS" object:nil];
        self.isAutoPlayOrShow = YES;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.decelerationRate = UIScrollViewDecelerationRateFast;
        self.voiceMsgID = 0;
        self.backgroundColor = ClearColor;
    }
    return self;
}



-(void)showImageInChat:(UIImage *) image
{
    self.delegate = nil;
    self.photoImageView = nil;
    
    for (UIView *aView in [self subviews]) {
        [aView removeFromSuperview];
    }
    UIImageView* view = [[UIImageView alloc]init];
    view.backgroundColor = ClearColor;
    [view setUserInteractionEnabled:YES];
    [self addSubview:view];
    
    CGSize sizeImage = image.size;
    
    
    CGFloat width = 0;
    CGFloat height = 0;
    CGFloat flag = sizeImage.width/sizeImage.height;
    if (flag>1) {
        width = BUBBLEVIEW_PIC_SIZE;
        height = BUBBLEVIEW_PIC_SIZE / flag;
    }
    else if (flag<1) {
        width = BUBBLEVIEW_PIC_SIZE * flag;
        height = BUBBLEVIEW_PIC_SIZE;
    }
    else if (flag==1) {
        width = BUBBLEVIEW_PIC_SIZE;
        height = BUBBLEVIEW_PIC_SIZE;
    }
    if (self.childMessage.messageType == SNSPMaterialTypeKVideo) {
        view.image = [self scaleToSize:image size:CGSizeMake(200, 150)];
        view.frame = CGRectMake(0, 0, 200, 150);
        
    }
    else
    {
    view.image = [self scaleToSize:image size:CGSizeMake(width, height)];
    view.frame = CGRectMake(0, 0, width, height);
    }
    if ([self.multiDelegate respondsToSelector:@selector(bubbleViewNeedResetFrameWithFrame:)]) {
        [self.multiDelegate bubbleViewNeedResetFrameWithFrame:view.frame];
    }
    if (self.childMessage.messageType == SNSPMaterialTypeKVideo) {
        [self addvideoInterFaceOn:view];
    }
    //    view.tag = self.tag;
}



-(void)showImage:(UIImage*)image
{
    
    for (UIView *aView in [self subviews]) {
        [aView removeFromSuperview];
    }
    // UIImageView* view = [[UIImageView alloc]init];
    //[view setUserInteractionEnabled:YES];
    
    UIImage *oldImage = image;
    if(image == nil){
        image = [UIImage imageNamed:@"imageIcon"];
    }
    CGRect rect = self.frame;
    CGSize sizeImage = image.size;
    UIImageView* view = [[UIImageView alloc]init];
    view.image = image;
    [view setUserInteractionEnabled:YES];
    
    //如果 长和宽都大于边界重新计算大小
    if(sizeImage.width > rect.size.width && sizeImage.height > rect.size.height)
    {
        if(sizeImage.width/sizeImage.height > rect.size.width/rect.size.height)
        {
            
            CGFloat width = rect.size.width;
            CGFloat height = rect.size.width*sizeImage.height/sizeImage.width;
            view.frame = CGRectMake(0,
                                    (rect.size.height - height)/2,
                                    width, height);
            
            
        }else{
            CGFloat height = rect.size.height;
            CGFloat width =  rect.size.height*sizeImage.width/sizeImage.height;
            view.frame = CGRectMake((rect.size.width - width)/2,
                                    0,
                                    width, height);
            
        }
    }else if(sizeImage.width > rect.size.width){
        //如果 宽大于边界重新计算大小
        CGFloat width = rect.size.width;
        CGFloat height = rect.size.width*sizeImage.height/sizeImage.width;
        view.frame = CGRectMake(0,
                                (rect.size.height - height)/2,
                                width, height);
        
        
        
    }else if(sizeImage.height > rect.size.height){
        //如果 长大于边界重新计算大小
        CGFloat height = rect.size.height;
        CGFloat width =  rect.size.height*sizeImage.width/sizeImage.height;
        view.frame = CGRectMake((rect.size.width - width)/2,
                                0,
                                width, height);
        
    }else{
        //如果长和宽都小于或者等于边界，剧中显示
        //        view.frame = CGRectMake((rect.size.width - sizeImage.width)/2,
        //                                (rect.size.height - sizeImage.height)/2,
        //                                sizeImage.width, sizeImage.height);
        if (sizeImage.height/rect.size.height>sizeImage.width/rect.size.width) {
            view.frame = CGRectMake((rect.size.width - sizeImage.width*rect.size.height/sizeImage.height)/2,
                                    0,
                                    sizeImage.width*rect.size.height/sizeImage.height, rect.size.height);
            
        }else{
            view.frame = CGRectMake(0,
                                    (rect.size.height - sizeImage.height*rect.size.width/sizeImage.width)/2,
                                    rect.size.width, sizeImage.height*rect.size.width/sizeImage.width);
            
            
        }
        
    }
    [self addSubview:view];
    
    if (oldImage) {
        self.photoImageView = view;
        self.delegate = self;
        [self setMaxMinZoomScalesForCurrentBounds];
    }
    
    //    [self addGestureRecognizerToView:view];
    if([view respondsToSelector:@selector(setNeedsDisplay)])
    {
        [view setNeedsDisplay];
    }
}


- (void)setMaxMinZoomScalesForCurrentBounds {
    
    // Reset
    self.maximumZoomScale = 1;
    self.minimumZoomScale = 1;
    self.zoomScale = 1;
    
    // Bail if no image
    if (_photoImageView.image == nil) return;
    
    // Reset position
    // Calculate Max
    CGFloat maxScale = 3;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // Let them go a bit bigger on a bigger screen!
        maxScale = 4;
    }
    
    // Set min/max zoom
    self.maximumZoomScale = maxScale;
    
    // Initial zoom
    // If we're zooming to fill then centralise
    self.scrollEnabled = NO;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.contentOffset.x < 0) {
        if ([self.multiDelegate respondsToSelector:@selector(scrollRight)]) {
            
            [self.multiDelegate scrollRight];
        }
    }
    else if (self.contentOffset.x + self.bounds.size.width > self.contentSize.width){
        if ([self.multiDelegate respondsToSelector:@selector(scrollLeft)]) {
            [self.multiDelegate scrollLeft];
        }
    }

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.photoImageView;
}

- (void)layoutSubviews {
    
    // Update tap view frame
    [super layoutSubviews];
    
    // Center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = self.bounds.size;
    CGRect frameToCenter = _photoImageView.frame;
    
    // Horizontally
    if (frameToCenter.size.width < boundsSize.width) {
        frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2.0);
    } else {
        frameToCenter.origin.x = 0;
    }
    
    // Vertically
    if (frameToCenter.size.height < boundsSize.height) {
        frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2.0);
    } else {
        frameToCenter.origin.y = 0;
    }
    
    // Center
    if (!CGRectEqualToRect(_photoImageView.frame, frameToCenter))
        _photoImageView.frame = frameToCenter;
    
}


- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    //    NSLog(@"%@ %@",NSStringFromCGRect(self.photoImageView.frame),NSStringFromCGSize(self.contentSize));
    if (self.frame.size.height < self.contentSize.height || self.frame.size.width < self.contentSize.width) {
        self.scrollEnabled = YES;
    } else {
        self.scrollEnabled = NO;
    }
}
-(void)setImage:(UIImage*)image
{
    
    [self showImage:image];
    
}

-(void)setVoiceType:(CHSVoiceType)voiceType
{
    
    self.delegate = nil;
    self.photoImageView = nil;
    
    _voiceType = voiceType;
    
    UILabel *timeLabel = (UILabel *)[self viewWithTag:133333];
    if (timeLabel) {
        [timeLabel removeFromSuperview];
        timeLabel = nil;
    }
    timeLabel = [[UILabel alloc] init];
    timeLabel.hidden = YES;
    timeLabel.backgroundColor = ClearColor;
    timeLabel.font = [UIFont systemFontOfSize:14.0];
    
    UIImageView *img_voice = (UIImageView *)[self viewWithTag:123647];
    if (img_voice) {
        [img_voice removeFromSuperview];
        img_voice = nil;
    }
    img_voice = [[UIImageView alloc] init];
    if (voiceType == CHSVoiceTypeSended) {
        timeLabel.textAlignment = NSTextAlignmentRight;
        timeLabel.textColor = [UIColor whiteColor];
        
        //img_voice.frame = CGRectMake(self.frame.size.width - 40, (self.frame.size.height-24)/2, 24, 30);
        img_voice.image = [UIImage imageNamed:@"audio_play_right_animate_03.png"];
        CGSize size = img_voice.image.size;
        img_voice.frame = CGRectMake(self.frame.size.width - 20 - size.width, 0, size.width, size.height);
        timeLabel.frame = CGRectMake(self.frame.size.width - 55 - size.width, 0, 30, self.frame.size.height);
        img_voice.animationImages=[NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"audio_play_right_animate_01.png"],
                                   [UIImage imageNamed:@"audio_play_right_animate_02.png"],
                                   [UIImage imageNamed:@"audio_play_right_animate_03.png"],nil ];
    }
    else if (voiceType == CHSVoiceTypeReceived) {
        timeLabel.textAlignment = NSTextAlignmentLeft;
        timeLabel.textColor = [UIColor blackColor];
        
        
        img_voice.image = [UIImage imageNamed:@"audio_play_left_animate_03.png"];
        
        CGSize size = img_voice.image.size;
        img_voice.frame = CGRectMake(20, (self.frame.size.height-size.height)/2, size.width, size.height);
        timeLabel.frame = CGRectMake(20 + size.width + 5, 0, 30, self.frame.size.height);
        
        img_voice.animationImages=[NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"audio_play_left_animate_01.png"],
                                   [UIImage imageNamed:@"audio_play_left_animate_02.png"],
                                   [UIImage imageNamed:@"audio_play_left_animate_03.png"],nil ];
    } else if (voiceType == CHSVoiceNoticeTypeReceived) {
        //        img_voice.image = [UIImage imageNamed:@"audio_play_left_animate_03.png"];
        //
        //        CGSize size = img_voice.image.size;
        //        img_voice.frame = CGRectMake(20, (self.frame.size.height-size.height)/2, size.width, size.height);
        //        timeLabel.frame =  CGRectMake(20, (self.frame.size.height-size.height)/2, size.width, size.height);
        //        img_voice.animationImages=[NSArray arrayWithObjects:
        //                                   [UIImage imageNamed:@"audio_play_left_animate_01.png"],
        //                                   [UIImage imageNamed:@"audio_play_left_animate_02.png"],
        //                                   [UIImage imageNamed:@"audio_play_left_animate_03.png"],nil ];
    }
    
    
    
    img_voice.tag = 123647;
    img_voice.animationDuration = 0.9f;
    
    //不能用nsintegerMax否者 会照成 跳到下一页面返回，无法停止动画的bug，用0最为合适，无重复播放动画
    img_voice.animationRepeatCount = 0;
    img_voice.userInteractionEnabled = YES;
    [self addSubview:img_voice];
    
    timeLabel.tag = 133333;
    [self addSubview:timeLabel];
    
}



-(void)handlImage
{
    [self showImageData];
    
}

-(void)showImageData
{
    self.delegate = nil;
    self.photoImageView = nil;
    UIImage *image = [self getImage];
    if (image == nil) {
        image = [UIImage imageNamed:@"imageIcon"];
        
    }
    [self showImageInChat:image];
    
}

-(UIImage *)getImage
{
    
    if (self.childMessage.fileUri) {
        UIImage *image = [UIImage imageWithData:[[NSData alloc] initWithBase64Encoding:self.childMessage.fileUri]];
        return image;
    }
    return nil;
}


- (BOOL)handlAudio
{
    NSData *data = [[NSFileManager defaultManager]  contentsAtPath:self.fileUri];
    
    if (data && data.length >= self.childMessage.fileLenth.longLongValue)
    {
        return YES;
    } else {
        return NO;
    }
}

-(BOOL)adjustFileExistWithPath:(NSString *)path
{
    NSData* data = [NSData dataWithContentsOfFile:path];
    if(data == nil) return NO;
    return YES;
}


-(void)handlRedPacket
{
    UIImage *image = [UIImage imageNamed:@"red-paper-big"];
    [self showFileWithImage:image];
}
- (void)handlFile
{
    //    NSString *localPath = nil;
    //    if (self.childMessage.isMine == CHBubbleMessageTypeReceived) {
    //
    //        if (self.childMessage.GroupId.length > 3) {
    //           localPath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:self.fileId] stringByAppendingPathComponent:self.fileUri];
    //        } else {
    //            localPath = [[[ChildHoodService defaultService] downLoadFilePathWithUserId:self.fileId] stringByAppendingPathComponent:self.fileUri];
    //        }
    //
    //    } else {
    //        localPath = [[[ChildHoodService defaultService] upLoadFilePathWithUserId:self.fileId] stringByAppendingPathComponent:self.fileUri];
    //    }
    //
    //    [self adjustFileExistWithPath:localPath];
    
    NSString *nameStr = [self.childMessage.fileName lowercaseString];
    
    NSString *fileIcon = [UIUtil getChatFileIconByName:nameStr];
    
    UIImage *image = [UIImage imageNamed:fileIcon];
    
    [self showFileWithImage:image];
}

- (void)showFileWithImage:(UIImage *)image
{
    
    self.delegate = nil;
    self.photoImageView = nil;
    
    
    for (UIView *aView in [self subviews]) {
        [aView removeFromSuperview];
    }
    UIImageView* view = [[UIImageView alloc]init];
    view.backgroundColor = ClearColor;
    [view setUserInteractionEnabled:YES];
    [self addSubview:view];
    
    CGSize sizeImage = image.size;
    
    UILabel *nameLabel = [[UILabel alloc] init];
    
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.numberOfLines = 3;
    
    nameLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    
    
    UILabel *sizeLabel = [[UILabel alloc] init];
    
    sizeLabel.textAlignment = NSTextAlignmentLeft;
    sizeLabel.numberOfLines = 3;
    
    sizeLabel.font = [UIFont systemFontOfSize:12.0f];
    
    
    NSString *title;
    NSString *str2 = [NSString stringWithFormat:@"%.2fK",self.childMessage.fileLenth.floatValue / 1024.0];
    if (self.redpacketInfo) {
        nameLabel.font = [UIFont boldSystemFontOfSize:15.0f];
        title = self.redpacketInfo;
        str2 = @"领取红包";
    }
    else{
    if (self.childMessage.GroupId.length > 3) {
        title = [UIUtil getGroupFileNameWithServerFileName:self.childMessage.fileName];
    } else {
        title = [UIUtil getFileNameWithServerFileName:self.childMessage.fileName];
    }
    }
    CGSize tiltSize = [UIUtil textSizeWithFont:[UIFont boldSystemFontOfSize:13.0f] width:130.0f height:50 text:title lineBreakMode:NSLineBreakByCharWrapping];
    
       nameLabel.text = title;
    sizeLabel.text = str2;
    
    if (self.childMessage.isMine == CHBubbleMessageTypeReceived) {
        nameLabel.textColor = [UIColor blackColor];
        sizeLabel.textColor = [UIColor blackColor];
        
    } else {
        
        nameLabel.textColor = [UIColor whiteColor];
        sizeLabel.textColor = [UIColor whiteColor];
    }
    
    [self addSubview:nameLabel];
    [self addSubview:sizeLabel];
    
    CGFloat width = 0;
    CGFloat height = 0;
    CGFloat flag = sizeImage.width/sizeImage.height;
    
    if (sizeImage.width > BUBBLEVIEW_PIC_SIZE - 20 || sizeImage.height > BUBBLEVIEW_PIC_SIZE - 20) {
        if (flag>1) {
            width = BUBBLEVIEW_PIC_SIZE - 20;
            height = (BUBBLEVIEW_PIC_SIZE - 20) / flag;
        }
        else if (flag<1) {
            height = BUBBLEVIEW_PIC_SIZE - 20;
            width = (BUBBLEVIEW_PIC_SIZE - 20)*flag;
        }
        else if (flag==1) {
            width = BUBBLEVIEW_PIC_SIZE- 20;
            height = BUBBLEVIEW_PIC_SIZE - 20;
        }
        view.image = [self scaleToSize:image size:CGSizeMake(width, height)];
    } else {
        width = sizeImage.width;
        height = sizeImage.height;
        view.image = image;
    }
    
    
   if (self.redpacketInfo) {
        view.frame = CGRectMake(20, 10, self.frame.size.height - 40, self.frame.size.height-40);
       nameLabel.frame = CGRectMake(CGRectGetMaxX(view.frame) + 10, 10, 130, tiltSize.height);
       sizeLabel.frame = CGRectMake(CGRectGetMaxX(view.frame) + 10, CGRectGetMaxY(nameLabel.frame)+8, 130, 20);

    }
    else
    {
        view.frame = CGRectMake(10, 10, width, height);
        view.center = CGPointMake(view.center.x, BUBBLEVIEW_PIC_SIZE / 2);
        nameLabel.frame = CGRectMake(CGRectGetMaxX(view.frame) + 10, 10, 130, tiltSize.height);
        
        sizeLabel.frame = CGRectMake(CGRectGetMaxX(view.frame) + 10, CGRectGetMaxY(nameLabel.frame), 130, 20);

    }
    
    //    sizeLabel.frame = CGRectMake(CGRectGetMaxX(view.frame) + 10, 60, 140, 15);
    
}
-(void) stopVoiceAnimation
{
    UIImageView *view = (UIImageView *)[self viewWithTag:123647];
    if (view) {
        
        if ([view isAnimating]) {
            [view stopAnimating];
        }
    }
}

- (void)showAudio
{
    UILabel *timelabel = (UILabel *)[self viewWithTag:133333];
    if (self.childMessage.SoundLenth == 0) {
        timelabel.hidden = YES;
        return;
    } else {
        timelabel.hidden = NO;
        [timelabel setText:[NSString stringWithFormat:@"%zd''",self.childMessage.SoundLenth]];
    }
    self.is_played = self.childMessage.isPlayed;
}

//开启wifi 自动下载语音和图片
- (void)setDownloadUrlWithFileName:(NSString *)fileName fileId:(NSString *)fileId chatType:(NSString *)chatType childMessage:(ChildHoodMessage *)message
{
    self.fileName = fileName;
    self.fileId = fileId;
    self.chatType = chatType;
    self.childMessage = message;
    
    
    if(message.messageType == SNSPMaterialTypeKImage||message.messageType == SNSPMaterialTypeKVideo)//可以对SNSPMaterialTypeKImageMessage做进一步区分
    {
        [self handlImage];
        
    }else if(message.messageType == SNSPMaterialTypeKImageMessage){
        
    }
    else if (message.messageType == SNSPMaterialTypeKAudio)
    {
        //        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopVoiceAnimation) name:@"STOPVOICEANIMATION" object:nil];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playVoice)];
        [tapGesture setNumberOfTapsRequired:1];
        [tapGesture setNumberOfTouchesRequired:1];
        [self addGestureRecognizer:tapGesture];
        self.fileUri = message.fileUri;
        [self showAudio];
        if(self.isAutoPlayOrShow)
        {
            
        }
    } else if (message.messageType == SNSPMaterialTypeKFile) {
        
        [self handlFile];
    }
    
    
    
    if (message.isMine == CHBubbleMessageTypeSended) {
        return;
    }
    self.setting = [[[CUserSettingMgr alloc] init] getUserSetting];
    
    // bug 6104 fixed by 荣则兵
    Reachability *r = [[CXmppMgr shareInstance] reachability];
    if([r currentReachabilityStatus] != ReachableViaWiFi && self.setting.IsOnlyWifiRcv){
        // 使用3G网络
        return;
    }
    
    __block NetAndAudioModel *netAndAudio = nil;
    [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
        if ([self.childMessage.fileName isEqualToString:obj.serFileName]) {
            netAndAudio = obj;
            *stop = YES;
        }
    }];
    if (netAndAudio) {
        return;
    }
    if (message.messageType == SNSPMaterialTypeKVideo) {
        if ([self handleVideoWithMessage:message]) {
            return;
        }
        if ([chatType isEqualToString:@"groupChat"]) {
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:fileName GroupId:fileId dataType:@"image" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                    [[ChildHoodService defaultService] saveImageWithFileName:fileName content:responseObject userId:fileId];
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                        self.processLal.hidden = NO;
                    //                        [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(totalBytesRead / (float)totalBytesExpectedToRead) * 100]];
                });
            } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
        } else {
            
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:message.fileName userId:fileId dataType:@"image" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                    [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
                
            } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
            
        }
        
        
    }
    
    if (message.messageType == SNSPMaterialTypeKImage) {
        if ([self handleImageWithMessage:message]) {
            return;
        }
        if ([chatType isEqualToString:@"groupChat"]) {
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:fileName GroupId:fileId dataType:@"image" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                    [[ChildHoodService defaultService] saveImageWithFileName:fileName content:responseObject userId:fileId];
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                        self.processLal.hidden = NO;
                    //                        [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(totalBytesRead / (float)totalBytesExpectedToRead) * 100]];
                });
            } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
        } else {
            
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:message.fileName userId:fileId dataType:@"image" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                    [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                        self.processLal.hidden = NO;
                    //                        [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(totalBytesRead / (float)totalBytesExpectedToRead) * 100]];
                });
                
            } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
            
        }
        
        
    } else if (message.messageType == SNSPMaterialTypeKAudio) {
        
        if ([self handlAudio]) {
            return;
        }
        
        if ([chatType isEqualToString:@"chat"]) {
            
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:fileName userId:fileId dataType:@"voice" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                
            } dataLenth:self.childMessage.fileLenth filePath:message.fileUri];
            
        } else if ([chatType isEqualToString:@"groupChat"]) {
            
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:fileName GroupId:fileId dataType:@"voice" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                
            } dataLenth:self.childMessage.fileLenth filePath:message.fileUri];
        }
    }
}


- (void)setIs_played:(MessageSoundPlayStatus)is_played
{
    _is_played = is_played;
    if ([self handlAudio]) {
        UIImageView *view = (UIImageView *)[self viewWithTag:123647];
        if (self.is_played == MessageSoundPlaying) {
            if (view) {
                
                [view startAnimating];
            }
        } else {
            if (view) {
                
                [view stopAnimating];
                
            }
        }
        
        return;
    }
    
}
#pragma mark 展示聊天图片

- (void)showImageWithMessage:(ChildHoodMessage *)message
{
    _childMessage = message;
    NSString *fileId;
    if (message.GroupId.length > 3) {
        fileId = message.GroupId;
    } else {
        if (message.isMine == CHBubbleMessageTypeReceived) {
            fileId = message.FriendUserId;
        } else {
            fileId = message.MineUserId;
        }
    }
    
    if ([self handleImageWithMessage:message]) {
        UIImage *image = [UIImage imageWithContentsOfFile:self.localFilePath];
        [self showImage:image];
        
    } else {
        [self showimageProcessWithMessage:message];
        
        __block NetAndAudioModel *netAndAudio = nil;
        [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
            if ([message.fileName isEqualToString:obj.serFileName]) {
                netAndAudio = obj;
                *stop = YES;
            }
        }];
        if (netAndAudio) {
            //            self.processLal.text = [NSString stringWithFormat:@"%.1f%%",netAndAudio.downPresValue * 100];
            [self.processLal updateWithTotalBytes:100 downloadedBytes:netAndAudio.downPresValue * 100];
            [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSData *data = [NSData dataWithContentsOfFile:self.localFilePath];
                    
                    //                    [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(data.length / message.fileLenth.floatValue) * 100]];
                    [self.processLal updateWithTotalBytes:100 downloadedBytes:(data.length / message.fileLenth.floatValue) * 100];
                });
                
            }];
            
            __block NetAndAudioModel *netAudio = netAndAudio;
            [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                if ([self handleImageWithMessage:message]) {
                    [self showImageWithMessage:message];
                } else {
                    [self showImage:nil];
                }
                
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self showImage:nil];
                [MBProgressHUD showError:@"网络连接不可用"];
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            }];
            
            return;
        }
        
        if (message.GroupId.length > 3) {
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:message.fileName GroupId:message.GroupId dataType:@"image" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
                
                if ([self handleImageWithMessage:message]) {
                    [self showImageWithMessage:message];
                } else {
                    [self showImage:nil];
                }
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self showImage:nil];
                [MBProgressHUD showError:@"网络连接不可用"];
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSData *data = [NSData dataWithContentsOfFile:self.localFilePath];
                    
                    //                    [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(data.length / message.fileLenth.floatValue) * 100]];
                    [self.processLal updateWithTotalBytes:message.fileLenth.floatValue downloadedBytes:data.length];
                    
                });
            } dataLenth:message.fileLenth filePath:self.localFilePath];
        } else {
            
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:message.fileName userId:fileId dataType:@"image" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
                
                if ([self handleImageWithMessage:message]) {
                    [self showImageWithMessage:message];
                } else {
                    [self showImage:nil];
                }
                
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                [self showImage:nil];
                [MBProgressHUD showError:@"网络连接不可用"];
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    self.processLal.hidden = NO;
                    NSData *data = [NSData dataWithContentsOfFile:self.localFilePath];
                    
                    //                    [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(data.length / message.fileLenth.floatValue) * 100]];
                    [self.processLal updateWithTotalBytes:100 downloadedBytes:(data.length / message.fileLenth.floatValue) * 100];
                    
                });
                
            } dataLenth:message.fileLenth filePath:self.localFilePath];
            
        }
    }
    
}

#pragma mark 展示聊天图片的下载进度
- (void)showimageProcessWithMessage:(ChildHoodMessage *)message
{
    
    
    self.delegate = nil;
    self.photoImageView = nil;
    
    
    for (UIView *aView in [self subviews]) {
        [aView removeFromSuperview];
    }
    
    UIImageView* view = [[UIImageView alloc]init];
    view.backgroundColor = ClearColor;
    [view setUserInteractionEnabled:YES];
    [self addSubview:view];
    
    UIImage *image = [UIImage imageWithData:[[NSData alloc] initWithBase64Encoding:message.fileUri]];
    if (image == nil) {
        image = [UIImage imageNamed:@"imageIcon"];
    }
    CGSize sizeImage = image.size;
    
    
    CGFloat width = 0;
    CGFloat height = 0;
    CGFloat flag = sizeImage.width/sizeImage.height;
    if (flag>1) {
        width = 150/sizeImage.height*sizeImage.width;
        height = 150;
    }
    else if (flag<1) {
        width = 150;
        height = 150/image.size.width*image.size.height;
    }
    else if (flag==1) {
        width = 150;
        height = 150;
    }
    
    view.image = [self scaleToSize:image size:CGSizeMake(width, height)];
    view.frame = CGRectMake(0, 0, width, height);
    //    view.tag = self.tag;
    view.center = CGPointMake(HARDWARE_SCREEN_WIDTH / 2.0, HARDWARE_SCREEN_HEIGHT / 2.0);

    RMDownloadIndicator *progress = [[RMDownloadIndicator alloc]initWithFrame:CGRectMake(0, 0, 60, 60) type:kRMMixedIndictor];
    progress.center = self.center;
    [progress setBackgroundColor:[UIColor clearColor]];
    [progress setFillColor:[UIColor whiteColor]];
    [progress setStrokeColor:[UIColor whiteColor]];
    progress.radiusPercent = 0.45;
    [progress loadIndicator];
    [self addSubview:progress];
    [self bringSubviewToFront:progress];
    self.processLal = progress;
    
    
}
- (BOOL)handleVideoWithMessage:(ChildHoodMessage*)message
{
    NSString *fileId;
    NSString *path;
    if (message.GroupId.length > 3) {
        fileId = message.GroupId;
        if (message.isMine == CHBubbleMessageTypeReceived) {
            path = [[[ChildHoodService defaultService] groupDownloadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            path = [[[ChildHoodService defaultService] groupUploadVideoPathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        }
        
    } else {
        if (message.isMine == CHBubbleMessageTypeReceived) {
            fileId = message.FriendUserId;
            path = [[[ChildHoodService defaultService] personalDownloadVideoPathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            fileId = message.MineUserId;
            path = [[[ChildHoodService defaultService] personalUploadVideoPathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        }
    }
    
    
    
    self.localFilePath = path;
    
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    if (data && data.length >= message.fileLenth.longLongValue) {
        return YES;
    }
    return NO;

}
- (BOOL)handleImageWithMessage:(ChildHoodMessage *)message
{
    NSString *fileId;
    NSString *path;
    if (message.GroupId.length > 3) {
        fileId = message.GroupId;
        if (message.isMine == CHBubbleMessageTypeReceived) {
            path = [[[ChildHoodService defaultService] groupDownloadImagePathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            path = [[[ChildHoodService defaultService] groupUploadImagePathWithGroupId:fileId] stringByAppendingPathComponent:message.fileName];
        }
        
    } else {
        if (message.isMine == CHBubbleMessageTypeReceived) {
            fileId = message.FriendUserId;
            path = [[[ChildHoodService defaultService] personalDownloadImagePathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        } else {
            fileId = message.MineUserId;
            path = [[[ChildHoodService defaultService] personalUploadImagePathWithUserId:fileId] stringByAppendingPathComponent:message.fileName];
        }
    }
    
    
    
    self.localFilePath = path;
    
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    if (data && data.length >= message.fileLenth.longLongValue) {
        return YES;
    }
    return NO;
}


#pragma  mark  播放声音
-(void) playVoice
{
    if ([self handlAudio]) {
        
        if (self.childMessage.isPlayed == MessageSoundNotPlay) {
            self.childMessage.isPlayed = MessageSoundPlayed;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVEREDPOT_NOTICE" object:self.childMessage];
            
        } else {
            
        }
        
        
        CHSAudioPlayer *player = [CHSAudioPlayer sharedInstance];
        player.delegate = self;
        [player playSoundWithURL:self.fileUri childMessage:self.childMessage];
        
    } else {
        
        __block NetAndAudioModel *netAndAudio = nil;
        [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
            if ([self.childMessage.fileName isEqualToString:obj.serFileName]) {
                netAndAudio = obj;
                *stop = YES;
            }
        }];
        if (netAndAudio) {
            self.childMessage.messageStatus = kMessageSending;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
            
            
            __block NetAndAudioModel *netAudio = netAndAudio;
            [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
                if ([self handlAudio]) {
                    
                    [self playVoice];
                }
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
                [MBProgressHUD showError:@"网络连接不可用"];
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            }];
            
            return;
        }
        
        if ([self.chatType isEqualToString:@"chat"]) {
            
            self.childMessage.messageStatus = kMessageSending;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:self.fileName userId:self.fileId dataType:@"voice" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
                if ([self handlAudio]) {
                    
                    [self playVoice];
                }
                
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                [MBProgressHUD showError:@"网络连接不可用"];
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                
            } dataLenth:self.childMessage.fileLenth filePath:self.fileUri];
            
        } else if ([self.chatType isEqualToString:@"groupChat"]) {
            
            self.childMessage.messageStatus = kMessageSending;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:self.fileName GroupId:self.fileId dataType:@"voice" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
                if ([self handlAudio]) {
                    
                    [self playVoice];
                }
                
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                self.childMessage.messageStatus = kMessageOK;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mutiViewDownLoadVoiceStatus" object:self.childMessage userInfo:nil];
                [MBProgressHUD showError:@"网络连接不可用"];
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                
            } dataLenth:self.childMessage.fileLenth filePath:self.fileUri];
        }
    }
}

//- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
//{
//    [[CHSAudioPlayer sharedInstance] handleNotification:NO];
//    UIImageView *view = (UIImageView *)[self viewWithTag:123647];
//    if (view)
//    {
//        if ([view isAnimating]) {
//            [view stopAnimating];
//        }
//    }
//}

- (void)CHSAudioPlayerDidFinishPlayWithPlayer:(AVAudioPlayer *)play succesfulFlag:(BOOL)flag childMessage:(ChildHoodMessage *)childMessage
{
    //    NSLog(@"11111");
    if (childMessage) {
        
        childMessage.isPlayed = MessageSoundPlayed;
    }
    UIImageView *view = (UIImageView *)[self viewWithTag:123647];
    if (view)
    {
        [view stopAnimating];
    }
    
}

- (void)CHSAudioPlayerStopPlayWithPlayer:(AVAudioPlayer *)play childMessage:(ChildHoodMessage *)childMessage
{
    //    NSLog(@"2222");
    if (childMessage) {
        
        childMessage.isPlayed = MessageSoundPlayed;
    }
    UIImageView *view = (UIImageView *)[self viewWithTag:123647];
    if (view)
    {
        [view stopAnimating];
        
    }
    
}
-(void) changeImage
{
    if (_voiceType == CHSVoiceTypeSended) {
        
    }
    else if (_voiceType == CHSVoiceTypeReceived) {
        
    }
}

-(void)addvideoInterFaceOn:(UIImageView*)imageView;
{
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self handleVideoWithMessage:self.childMessage];
    imageView.userInteractionEnabled = YES;
    NSURL *videoFileURL = [NSURL fileURLWithPath:self.localFilePath isDirectory:NO];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:videoFileURL options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    self.player.volume = 0 ;
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = imageView.bounds;
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [imageView.layer addSublayer:_playerLayer];
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton addTarget:self action:@selector(downloadVideo:) forControlEvents:UIControlEventTouchUpInside];
    [_playButton setImage:[UIImage imageNamed:@"video_icon"] forState:UIControlStateNormal];
    _playButton.frame = imageView.bounds;
    [imageView addSubview:_playButton];
}

-(void)downloadVideo:(UIButton*)sender
{
    sender.hidden = YES;
    if ([self handleVideoWithMessage:self.childMessage]) {
        
        [self.player play];
    }
    else
    {
        RMDownloadIndicator *progress = [[RMDownloadIndicator alloc]initWithFrame:CGRectMake(0, 0, 60, 60) type:kRMMixedIndictor];
        progress.center = self.center;
        [progress setBackgroundColor:[UIColor clearColor]];
        [progress setFillColor:[UIColor whiteColor]];
        [progress setStrokeColor:[UIColor whiteColor]];
        progress.radiusPercent = 0.45;
        [progress loadIndicator];
        [sender.superview addSubview:progress];
        [sender.superview bringSubviewToFront:progress];
        self.processLal = progress;

        __weak typeof (self) weakSelf = self;
        NSString *fileId;
        if (self.childMessage.GroupId.length > 3) {
            fileId = self.childMessage.GroupId;
        } else {
            if (self.childMessage.isMine == CHBubbleMessageTypeReceived) {
                fileId = self.childMessage.FriendUserId;
            } else {
                fileId = self.childMessage.MineUserId;
            }
        }

    if (self.childMessage.GroupId.length > 3) {
        [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:self.childMessage.fileName GroupId:self.childMessage.GroupId dataType:@"video" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            //                [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
            
            if ([self handleVideoWithMessage:self.childMessage]) {
                [self.processLal removeFromSuperview];
                NSURL *videoFileURL = [NSURL fileURLWithPath:self.localFilePath isDirectory:NO];
                AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:videoFileURL options:nil];
                weakSelf.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
                weakSelf.player = [AVPlayer playerWithPlayerItem:_playerItem];
                weakSelf.player.volume = 0 ;
                weakSelf.playerLayer.player = weakSelf.player;
                [weakSelf.player play];
            }

        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD showError:@"网络连接不可用"];
        } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSData *data = [NSData dataWithContentsOfFile:self.localFilePath];
                
                //                    [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(data.length / message.fileLenth.floatValue) * 100]];
                [self.processLal updateWithTotalBytes:self.childMessage.fileLenth.floatValue downloadedBytes:data.length];
                
            });
        } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
    } else {
        
        [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:self.childMessage.fileName userId:fileId dataType:@"video" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            //                [[ChildHoodService defaultService] saveImageWithFileName:message.fileName content:responseObject userId:fileId];
            
            if ([self handleVideoWithMessage:self.childMessage]) {
                [self.processLal removeFromSuperview];
                NSURL *videoFileURL = [NSURL fileURLWithPath:self.localFilePath isDirectory:NO];
                AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:videoFileURL options:nil];
                weakSelf.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
                weakSelf.player = [AVPlayer playerWithPlayerItem:_playerItem];
                weakSelf.player.volume = 0 ;
                weakSelf.playerLayer.player = weakSelf.player;
                [weakSelf.player play];
            }
            
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD showError:@"网络连接不可用"];
        } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                    self.processLal.hidden = NO;
                NSData *data = [NSData dataWithContentsOfFile:self.localFilePath];
                
                //                    [self.processLal setText:[NSString stringWithFormat:@"%.1f%%",(data.length / message.fileLenth.floatValue) * 100]];
                [self.processLal updateWithTotalBytes:100 downloadedBytes:(data.length / self.childMessage.fileLenth.floatValue) * 100];
                
            });
            
        } dataLenth:self.childMessage.fileLenth filePath:self.localFilePath];
        
    }
    }
}
-(void)avPlayerItemDidPlayToEnd:(NSNotification*)notificaiton
{
    if ((AVPlayerItem *)notificaiton.object != _playerItem) {
        return;
    }
    [_playerItem seekToTime:kCMTimeZero];
    [self.player play];
}
@end



//-(void)showImageInfullScreen:(UIImage*)image
//{
//
//    self.delegate = nil;
//    self.photoImageView = nil;
//
//
//    for (UIView *aView in [self subviews]) {
//        [aView removeFromSuperview];
//    }
//    CGRect rect = self.frame;
//    UIImageView* view = [[UIImageView alloc]initWithImage:image];
//    //    CGSize size = image.size
//    //    ;
//    //    rect.size.height = size.height;
//    //    rect.size.width = size.width;
//    view.clipsToBounds = YES;
//    [view setUserInteractionEnabled:YES];
//
//    view.frame = rect;
//    view.tag = self.tag;
//
//    [self addSubview:view];
//
//    [view setNeedsDisplay];
//
//
//}
//-(void)showImage2XInfullScreen:(UIImage*)image{
//
//
//    self.delegate = nil;
//    self.photoImageView = nil;
//
//
//    for (UIView *aView in [self subviews]) {
//        [aView removeFromSuperview];
//    }
//    CGRect rect = self.frame;
//    UIImageView* view = [[UIImageView alloc]initWithImage:image];
//    CGSize size = image.size
//    ;
//    rect.size.height = size.height*2;
//    rect.size.width = size.width*2;
//    view.clipsToBounds = YES;
//    [view setUserInteractionEnabled:YES];
//
//    view.frame = rect;
//    view.center = self.center;
//
//
//    view.tag = self.tag;
//
//    [self addSubview:view];
//    [view setNeedsDisplay];
//}
//
////-(NSString*)localFileName:(BOOL)md5Flag
////{
////    if(md5Flag){
////        NSString* md5 = nil;
////        if(_fileUri != nil )
////        {
////            md5 = [UIUtil md5:_fileUri];
////        }
////        //        return [NSString stringWithFormat:@"%@%@", [ChildHoodService defaultService].childHoodUser.resourcePath, md5];
////    }
////    //    return [NSString stringWithFormat:@"%@%@", [ChildHoodService defaultService].childHoodUser.resourcePath, _fileUri];
////    return nil;
////}
//
//
//-(void)showImage:(UIImage *)image type:(int32_t)type1
//{
//
//    self.delegate = nil;
//    self.photoImageView = nil;
//
//
//    if(image == nil)
//    {
//        return;
//    }
//    if (type1==SNSPMaterialTypeKImageMessage) {
//        for (UIView *aView in [self subviews]) {
//            [aView removeFromSuperview];
//        }
//        // UIImageView* view = [[UIImageView alloc]init];
//        //[view setUserInteractionEnabled:YES];
//
//        CGRect rect = self.frame;
//        CGSize sizeImage = image.size;
//        UIImageView* view = [[UIImageView alloc]initWithImage:image];
//        [view setUserInteractionEnabled:YES];
//
//
//
//        //如果 长和宽都大于边界重新计算大小
//        if(sizeImage.width > rect.size.width && sizeImage.height > rect.size.height)
//        {
//            if(sizeImage.width/sizeImage.height > rect.size.width/rect.size.height)
//            {
//
//                CGFloat width = rect.size.width;
//                CGFloat height = rect.size.width*sizeImage.height/sizeImage.width;
//                view.frame = CGRectMake(0,
//                                        (rect.size.height - height)/2,
//                                        width, height);
//
//
//            }else{
//                CGFloat height = rect.size.height;
//                CGFloat width =  rect.size.height*sizeImage.width/sizeImage.height;
//                view.frame = CGRectMake((rect.size.width - width)/2,
//                                        0,
//                                        width, height);
//
//            }
//        }else if(sizeImage.width > rect.size.width){
//            //如果 宽大于边界重新计算大小
//            CGFloat width = rect.size.width;
//            CGFloat height = rect.size.width*sizeImage.height/sizeImage.width;
//            view.frame = CGRectMake(0,
//                                    (rect.size.height - height)/2,
//                                    width, height);
//
//
//
//        }else if(sizeImage.height > rect.size.height){
//            //如果 长大于边界重新计算大小
//            CGFloat height = rect.size.height;
//            CGFloat width =  rect.size.height*sizeImage.width/sizeImage.height;
//            view.frame = CGRectMake((rect.size.width - width)/2,
//                                    0,
//                                    width, height);
//
//        }else{
//            //如果长和宽都小于或者等于边界，剧中显示
//            //        view.frame = CGRectMake((rect.size.width - sizeImage.width)/2,
//            //                                (rect.size.height - sizeImage.height)/2,
//            //                                sizeImage.width, sizeImage.height);
//
//
//            if (sizeImage.height/rect.size.height>sizeImage.width/rect.size.width) {
//                view.frame = CGRectMake((rect.size.width - sizeImage.width*rect.size.height/sizeImage.height)/2,
//                                        0,
//                                        sizeImage.width*rect.size.height/sizeImage.height, rect.size.height);
//
//            }else{
//                view.frame = CGRectMake(0,
//                                        (rect.size.height - sizeImage.height*rect.size.width/sizeImage.width)/2,
//                                        rect.size.width, sizeImage.height*rect.size.width/sizeImage.width);
//            }
//        }
//
//        view.tag = self.tag;
//
//        /*  UITapGestureRecognizer *scanImg     = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanImgMethod:)] autorelease];
//
//         [view addGestureRecognizer:scanImg];
//         */
//        //image.size =
//        [self addSubview:view];
//        [self addSubview:self.processLal];
//        CGRect ff = self.frame;
//        self.processLal.frame = CGRectMake((ff.size.width - 40)/2, (ff.size.height - 20)/2, 40, 20);
//
//        self.processLal.text = @"0%";
//        self.processLal.textColor = [UIColor whiteColor];
//        self.processLal.backgroundColor = [UIColor clearColor];
//        self.processLal.layer.backgroundColor = [UIColor colorWithHue:.48 saturation:.45 brightness:.45 alpha:.6].CGColor;
//        self.processLal.layer.cornerRadius = 5.0f;
//
//        [self bringSubviewToFront:self.processLal];
//
//        [view setNeedsDisplay];
//
//    }
//}
//
//
//-(void)showImageDataWithType:(int32_t)type1{
//
//
//    self.delegate = nil;
//    self.photoImageView = nil;
//
//
//    if (type1==SNSPMaterialTypeKImageMessage) {
////        NSData* data = [NSData dataWithContentsOfFile:[self localFileName:NO]];
////        if(data == nil) data = [NSData dataWithContentsOfFile:[self localFileName:YES]];
//
//        UIImage *showImage =  [self getImage];
////        if(data == nil || [data length] ==0)
//        if(showImage == nil)
//        {
//            for (UIView *aView in [self subviews]) {
//                [aView removeFromSuperview];
//            }
//
//            if(self.showProgress){
//                CGRect ff = self.frame;
//                self.processLal.frame = CGRectMake((ff.size.width - 40)/2, (ff.size.height - 20)/2, 40, 20);
//                self.processLal.hidden = NO;
//                self.processLal.text = @"0%";
//                self.processLal.textColor = [UIColor whiteColor];
//                self.processLal.backgroundColor = [UIColor clearColor];
//                self.processLal.layer.backgroundColor = [UIColor colorWithHue:.48 saturation:.45 brightness:.45 alpha:.6].CGColor;
//                self.processLal.layer.cornerRadius = 5.0f;
//                [self addSubview:self.processLal];
//                [self bringSubviewToFront:self.processLal];
//            }
//            else{
//
//                UIImage*    image = [UIImage imageNamed:@"imageIcon"];
//
//                if(_isFromChat){
//                    [self showImageInChat:image];
//                }else{
//                    [self showImage:image type:_type];
//                }
//
//            }
//
//        }
//        else
//        {
//            UIImage *image = showImage;
//            if (_isFromChat) {
//                [self showImageInChat:image];
//            }
//            else
//            {
//                [self showImage:image type:_type];
//            }
//        }
//
//    }
//}


//-(void)setMultimediaFileUri:(NSString*)fileUri type:(int32_t)type
//{
//    if(fileUri == nil){
//
//        for (UIView *aView in [self subviews]) {
//            [aView removeFromSuperview];
//        }
//
//        return;
//    }
//    self.fileUri = [NSString stringWithFormat:@"%@",fileUri];
//    _type = type;
//
//    if(_type == SNSPMaterialTypeKImage)//可以对SNSPMaterialTypeKImageMessage做进一步区分
//    {
//        [self handlImage];
//
//    }else if(_type == SNSPMaterialTypeKImageMessage){
//        [self handlImageWithType:SNSPMaterialTypeKImageMessage];
//    }
//    else if (_type == SNSPMaterialTypeKAudio)
//    {
////        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopVoiceAnimation) name:@"STOPVOICEANIMATION" object:nil];
//        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playVoice)];
//        [tapGesture setNumberOfTapsRequired:1];
//        [tapGesture setNumberOfTouchesRequired:1];
//        [self addGestureRecognizer:tapGesture];
//        if(self.isAutoPlayOrShow)
//        {
//
//        }
//    } else if (_type == SNSPMaterialTypeKFile) {
//        [self handlFile];
//    }
//
//}
